package com.thread;

import java.util.concurrent.TimeUnit;

public class ThreadSingleClass010_volatile {

    public static volatile ThreadSingleClass010_volatile INSTANCE;

    public static ThreadSingleClass010_volatile getInstance() {

        if (INSTANCE == null) {// volatile 保证可见性 在返回主内存之后，并发情况下就很少去获得锁
            //试图进行锁粒度优化，然而不行，存在多并发问题
            synchronized (ThreadSingleClass010_volatile.class) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //双重检查
                if(INSTANCE == null)INSTANCE = new ThreadSingleClass010_volatile();
            }
        }

        return INSTANCE;
    }

    private ThreadSingleClass010_volatile() {
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; ++i) {
            new Thread(() -> {
                System.out.println(ThreadSingleClass010_volatile.getInstance().hashCode());
                ;
            }).start();
        }
    }
}
